TOOL.Category = '(Malawar)'
TOOL.Name = '#Launcher'
TOOL.Command = nil
TOOL.ConfigName = ''

TOOL.ClientConVar['keydown'] = ''
TOOL.ClientConVar['type'] = 'malawar_rocket'
TOOL.ClientConVar['model'] = 'models/props_combine/breenglobe.mdl'
TOOL.ClientConVar['camera'] = '0'

cleanup.Register('launchers')


if ( CLIENT ) then
	language.Add( 'Tool_launcher_name', 'Launcher Spawner (Malawar)' )
	language.Add( 'Tool_launcher_desc', 'Create Launchers attached to any surface.' )
	language.Add( 'Tool_launcher_0', 'Click somewhere to attach a Launcher.' )

	language.Add( 'Undone_launcher', 'Launcher Undone' )
	language.Add( 'Cleanup_launchers', 'Launcher' )
	language.Add( 'Cleaned_launcher', 'Cleaned up all Launchers' )
	language.Add( 'SBoxLimit_launchers', 'Maximum Launchers Reached' )
end

launcher_ents = {
  malawar_rocket = {
    name = "Dumbfire Rocket"
	},
  malawar_heatseeker = {
	name = "Heatseeker (anti-thruster)"
	}
}

launcher_models = {
	{ 'Globe', 'models/props_combine/breenglobe.mdl' },
	{ 'Chinese Take Out', 'models//props_junk/garbage_takeoutcarton001a.mdl' },
	{ 'Plastic Bucket', 'models/props_junk/plasticbucket001a.mdl' },
	{ 'Metal Bucket', 'models/props_junk/MetalBucket01a.mdl' },
	{ 'Propane Tank', 'models/props_junk/propane_tank001a.mdl' },
	{ 'Tall Lamp', 'models/props_interiors/Furniture_Lamp01a.mdl' },
	{ 'Trash Can', 'models/props_trainstation/trashcan_indoor001b.mdl' }
}


function TOOL:LeftClick( trace )
	if trace.Entity && (trace.Entity:IsPlayer() ) then return false end
	
	if(CLIENT) then
		return true
	end

	if(!SERVER) then return false end

	if ( !self:GetSWEP():CheckLimit( "launchers" ) ) then return false end

	local ply = self:GetOwner()
	local Pos = trace.HitPos
	local Ang = trace.HitNormal:Angle()
	Ang.pitch = Ang.pitch + 90
	
	local keydown 			= self:GetClientNumber( 'keydown' ) 
	local launcher_type		= self:GetClientInfo('type')
	local launcher_model	= self:GetClientInfo('model')
	local camera			= self:GetClientNumber('camera')
	ent = MakeLauncher( ply, Ang, Pos, keydown, launcher_type, launcher_model, camera )
	ent:SetPos( trace.HitPos - trace.HitNormal * ent:OBBMins().z)
	
	if ( trace.Entity:IsValid() ) then
		local const = constraint.Weld(ent, trace.Entity,0, trace.PhysicsBone, 0, systemmanager )
		nocollide = constraint.NoCollide( ent, trace.Entity, 0, trace.PhysicsBone )
		trace.Entity:DeleteOnRemove( ent )
	end

	undo.Create('Launcher')
		undo.AddEntity( ent)
		undo.AddEntity( const )
		undo.AddEntity( nocollide )
		undo.SetPlayer( ply )
	undo.Finish()


	ply:AddCleanup( 'launchers', thruster )
	ply:AddCleanup( 'launchers', const )
	ply:AddCleanup( 'launchers', nocollide )
	
	return true
end

if SERVER then 
    CreateConVar('sbox_maxlaunchers',10)
	
	function MakeLauncher( ply, Ang, Pos, keydown, launcher_type, model, camera )
		if ( !ply:CheckLimit( "launchers" ) ) then return nil end
		local ent = ents.Create( 'malawar_launcher' )
			if !ent:IsValid() then return false end
			ent:SetModel( model )
			ent:SetAngles(Ang)
			ent:SetPos(Pos)
		ent:Spawn()

		ent:SetVar('Owner',ply)
		
		numpad.OnDown(ply, keydown, 'Launcher_On', ent, 1)
		numpad.OnUp(ply, keydown, 'Launcher_Off', ent, 1)

		local rtable = {
			keydown = keydown,
			launcher_type = launcher_type,
			model = model,
			camera = camera
			}
			
			
		table.Merge(ent:GetTable(), rtable )
		
		ply:AddCount('launchers', ent)
		
		return ent
	end
	
	duplicator.RegisterEntityClass( 'launcher', MakeRepulsor,  'Ang', 'Pos', 'keydown', 'launcher_type', 'model', 'camera' )
	
	local function ResetCamera( ent, player )
		player:SetViewEntity(player)
	end
	
	local function Launcher_On( pl, ent, mul )
		if (!ent:IsValid()) then return false end
		local launcherDelay = 1
		ent:GetTable().Timer = ent:GetTable().Timer or CurTime() - launcherDelay
		if CurTime() < ent:GetTable().Timer + launcherDelay then return true end
		
			local spawn = ents.Create( ent:GetVar('launcher_type', nil) )
				local ang = ent:GetAngles()
				spawn:GetTable():SetAngles(ang)
				local adjust = ent:OBBMaxs().z + spawn:OBBMaxs().z + 5
				spawn:SetPos(ent:GetPos() + (ent:GetUp()*adjust))
				constraint.NoCollide( spawn, ent, 0, 0 )
				spawn:SetVar('Owner',pl)
				phys = spawn:GetPhysicsObject()
				if phys:IsValid() then
					phys:SetVelocity(ent:GetVelocity())
				end
				spawn:SetCollisionGroup( COLLISION_GROUP_INTERACTIVE_DEBRIS )
			spawn:Spawn()
		if util.tobool(ent:GetVar('camera','0')) then -- we have to make a junk prop so it aligns right :((
			local target = ents.Create('prop_dynamic')
			target:SetModel('models//props_lab/Cleaver.mdl')
			local viewAngle = (ent:GetUp():Angle())
			target:SetAngles(viewAngle)
			target:SetPos(spawn:GetPos() + ent:GetUp() * (spawn:OBBMaxs().z + 5))
			target:SetParent(spawn)
			target:Spawn()
			target:SetColor( 0,0,0,0)
			pl:SetViewEntity( target )
			spawn:CallOnRemove('RemoveMissileCamera', ResetCamera, pl)
		end
		ent:GetTable().Timer = CurTime()
		return true
	end

	local function Launcher_Off( pl, ent, mul )
		if (!ent:IsValid()) then return false end

		return true
	end

	numpad.Register( "Launcher_On", Launcher_On )
	numpad.Register( "Launcher_Off", Launcher_Off )	
end

function TOOL.BuildCPanel( cp )
	cp:AddControl( 'Header', { Text = '#Tool_launcher_name', Description	= '#Tool_launcher_desc' }  )

	local combo = {}
	combo.Label = 'Launcher Type'
	combo.MenuButton = 1
	combo.Folder = 'settings/menu/main/construct/cannon/'
	combo.Options = {}
	
	for ent_type, edata in pairs(launcher_ents) do
		combo.Options[edata.name] = { launcher_type = ent_type }
	end
	cp:AddControl('ComboBox', combo) 

	combo = {}
	combo.Label = 'Launcher Model'
	combo.MenuButton = 1
	combo.Folder = 'settings/menu/main/construct/cannon/'
	combo.Options = {}
	
	for k, v in pairs(launcher_models) do
	  combo.Options[v[1]] = { launcher_model = v[2] }
	end

	cp:AddControl('ComboBox', combo) 

	cp:AddControl( "Checkbox", { Label = "Missile Cam", Command = "launcher_camera" } )

	cp:AddControl('Numpad', { Label = 'Fire:', ButtonSize = '22', Command = 'launcher_keydown' } )
	
end

function TOOL:UpdateGhostRepulsor( ent, player )

	if ( !ent ) then return end
	if ( !ent:IsValid() ) then return end

	local tr 	= utilx.GetPlayerTrace( player, player:GetCursorAimVector() )
	local trace 	= util.TraceLine( tr )
	if (!trace.Hit) then return end
	
	if (trace.Entity && trace.Entity:GetClass() == "malawar_repulsor" || trace.Entity:IsPlayer() ) then
	
		ent:SetNoDraw( true )
		return
		
	end
	
	local Ang = trace.HitNormal:Angle()
	Ang.pitch = Ang.pitch + 90
	ent:SetAngles( Ang )
	
	local min = ent:OBBMins()
	ent:SetPos( trace.HitPos - trace.HitNormal * min.z )
	
	ent:SetNoDraw( false )
	
end


function TOOL:Think()
	local model	= self:GetClientInfo('model')
	
	if (!self.GhostEntity || !self.GhostEntity:IsValid() || self.GhostEntity:GetModel() != model) then
		self:MakeGhostEntity( model, Vector(0,0,0), Angle(0,0,0) )
	end
	
	self:UpdateGhostRepulsor( self.GhostEntity, self:GetOwner() )
end


